﻿import numpy
import random


class World:

    def __init__(self, (w, h)):
        self.w = w
        self.h = h
        self.clear()

    def clear(self):
        self.cells = numpy.zeros((self.w, self.h), int)

    def count_neighbors(self, (x, y)):
        neighbors = 0
        for xmod in range(-1, 2):
            for ymod in range(-1, 2):
                if not (xmod == 0 and ymod == 0) and \
                    (0 <= (x + xmod) < self.w) and \
                    (0 <= (y + ymod) < self.h):
                    neighbors += self.cells[x + xmod][y + ymod]
        return neighbors

    def deliver_fate(self):
        temp = numpy.zeros((self.w, self.h), int)
        for x in range(self.w):
            for y in range(self.h):
                neighbors = self.count_neighbors((x, y))
                alive     = self.cells[x][y]
                if (neighbors in (2, 3) and alive) or \
                   (neighbors == 3 and not alive):
                    temp[x][y] = 1
        self.cells = temp.copy()

    def randomize(self):
        self.clear()
        cell_count = random.randint(1, self.w * self.h)
        for n in range(cell_count):
            x = random.randint(0, self.w-1)
            y = random.randint(0, self.h-1)
            self.cells[x][y] = 1
